package com.example.video_demo

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.os.Environment
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.io.File

class MainActivity : AppCompatActivity() {
    private var yuv: ByteArray? = null
    private var bmp: Bitmap? = null
    private var width = 1920
    private var height = 1920

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        bmp = BitmapFactory.decodeResource(resources, R.drawable.lenna)
        width = bmp?.width ?: 0
        height = bmp?.height ?: 0
        findViewById<ImageView>(R.id.img_rgb_to_yuv).setOnLongClickListener {
            val dir =
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
            val dest = File(dir, "default_lenna.yuv")
            Utils.writeFile(dest.absolutePath, yuv)
            Toast.makeText(baseContext, "save success", Toast.LENGTH_LONG).show()
            true
        }
    }

    fun rgbToYuv(view: View) {
        var pixels: IntArray? = IntArray(width * height)
        bmp?.getPixels(pixels, 0, width, 0, 0, width, height)
        yuv = Utils.rgb2YCbCr420(pixels, width, height)
        val bmp = Utils.yuvToBitMap(yuv, width, height)

        findViewById<ImageView>(R.id.img_rgb_to_yuv).setImageBitmap(bmp)
    }

    fun yuvToRgb(view: View) {
        val bmp = Utils.yuvToBitMap(yuv, width, height)
        findViewById<ImageView>(R.id.img_yuv_to_rgb).setImageBitmap(bmp)
    }
}